package com.cff.shorturl.http.handler.inter;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.cff.shorturl.cache.Cache;
import com.cff.shorturl.db.DbFactory;
import com.cff.shorturl.db.DbManager;
import com.cff.shorturl.http.body.HttpRequestMsg;
import com.cff.shorturl.http.body.HttpResponseMsg;
import com.cff.shorturl.http.handler.ResourceHandler;
import com.cff.shorturl.manager.CacheManager;
import com.cff.shorturl.task.LimitLogTask;
import com.cff.shorturl.task.TreadManager;
import com.cff.shorturl.util.DateUtil;
import com.cff.shorturl.util.StringUtil;

public class AuthResourceHandler extends ResourceHandler {

	@Override
	public HttpResponseMsg handle(HttpRequestMsg httpRequestMsg) {
		String url = httpRequestMsg.getUrl();

		Cache cache = CacheManager.getInstance().getCache(CacheManager.RESOURCE);
		if (cache == null) {
			CacheManager.getInstance().putCache(CacheManager.RESOURCE, new Cache() {
				@Override
				public void init() {
					setKey(CacheManager.RESOURCE);
					setStart(System.currentTimeMillis());
					setTimeOut(-1);
					setHasLoad(true);
				}

				@Override
				public void loadToCache() throws SQLException {
					DbManager db = DbFactory.createDbManager();
					String sql = "SELECT * FROM t_short_resource";
					List<Map<String, String>> resources = db.query(sql, null);
					Map<String, Integer> value = new ConcurrentHashMap<String, Integer>();
					for (Map<String, String> item : resources) {
						String resource = item.get("resource");
						Integer id = Integer.parseInt(item.get("id"));
						value.put(resource, id);
					}
					this.setValue(value);
				}

			});
			cache = CacheManager.getInstance().getCache(CacheManager.RESOURCE);
		}
		if(!checkReourceAuth(cache,url))return null;

		Map<String, Object> params = httpRequestMsg.getParams();
		String appKey = (String) params.get("appKey");
		String appId = (String) params.get("appId");
		if (StringUtil.isEmpty(appKey) || StringUtil.isEmpty(appId)) {
			return httpRequestMsg.getReponseWithoutAuth();
		}
		DbManager db = DbFactory.createDbManager();
		String sql = "select su.limit from t_short_user su,t_short_group sg,t_short_resource sr "
				+ "where su.group = sg.group and sg.resourceId = sr.id and su.appId= ? and "
				+ "su.appKey=? and su.valid ='0' and sr.resource = ?";
		try {
			int limit = db.queryInt(sql, new Object[] { appId, appKey, url });
			if (limit < 1)
				return httpRequestMsg.getReponseWithoutAuth();
			String sqlCount = "select count(1) from t_short_log where appId = ? and date = ?";
			int countLimit = db.queryInt(sqlCount,
					new Object[] { appId, DateUtil.format(new Date(), DateUtil.SimpleDatePattern) });
			if (countLimit >= limit)
				return httpRequestMsg.getReponseWithMsg("当日额度已用完！");

			LimitLogTask task = new LimitLogTask();
			task.setAppId(appId);
			task.setDate(new Date());
			task.setAction(url);
			TreadManager.submit(task);

		} catch (Exception e) {
			e.printStackTrace();
			return httpRequestMsg.getReponseInternalError();
		}
		return null;
	}
	
	/**
	 * 资源是否被保护
	 * @param cache
	 * @param url
	 * @return
	 */
	public boolean checkReourceAuth(Cache cache,String url){
		Map<String, Integer> value = (Map<String, Integer>) cache.getValue();
		if(value.get(url)==null){
			return false;
		}
		return true;
	}

}
